<script lang="ts" setup>
import * as echarts from 'echarts';
import {onActivated, onMounted, onUnmounted, reactive, ref, watch} from 'vue';
import stomp from "@/variable/Stomp";
import {IMessage} from "@stomp/stompjs";
import {regionTree} from "@/api/site";
import ComTreeSelect from "@/components/ComTreeSelect.vue";
import getThemeConfig from "@/variable/echarts";
import { type } from 'os';

const props = defineProps<{
  id: string,
  chartId:string
}>()

let data = [];
// for (let i = 1; i < 20000; i++) {
//   let now = new Date((base += oneDay));
//   data.push([+now, Math.round((Math.random() - 0.5) * 20 + data[i - 1][1])]);
// }

let myChart: any
let option = getThemeConfig()
const initEcharts = () => {
  const chartDom = document.getElementById(props.chartId)
  if (chartDom == null) {
    return
  }
  chartDom.removeAttribute('_echarts_instance_')
  myChart = echarts.init(chartDom);
  myChart.setOption(option);
  window.addEventListener("resize", myChart.resize)
}

const passageway={
  1:'E-W',
  2:'N-S',
  3:'U-D',
  4:'E-W',
  5:'N-S',
  6:'U-D',
}

const connectStomp = () => {
  stomp.subscribe('/topic/wc', (message) => {
    if (message.id !== conditionForm.station) {
      return
    }
    message.pcList.forEach((pc: object, idx: Number) => {
      if (!data[idx]) {
        data[idx] = []
      }
      for (let i = 0; i < 50; i++) {
        if (i % conditionForm.sample == 0) {
          const value = pc['val' + i]
          data[idx].push([message.startTime * 1000 + 5 * i, value])
          const count = conditionForm.timeRange / 0.005 / conditionForm.sample
          if (data[idx].length > count) {
            data[idx].splice(0, data[idx].length - count)
          }
        }
      }

    })
    const series = []
    const legendData = []
    for (let i = (conditionForm.access == 1 ? 0 : 3); i < (conditionForm.access == 1 ? 3 : 6); i++) {
      let name = passageway[(i + 1)];
      series.push({
        data: data[i],
        name: name,
        type: 'line',
        smooth: true,
        symbol: 'none'
      })
      legendData.push(name)
    }
    myChart.setOption({
      series,
      legend: {
        data: legendData
      }
    });
  })
}

// watch(() => props.stateData, value => {
//   option.legend.data = value[0] ? value[0].slice(1) : []
//   for (let i = 0; i < option.legend.data.length; i++) {
//     if (option.legend.data[i] === '已结案') {
//       option.legend.data[i] = processStatusMap['10']
//       break
//     }
//   }
//   option.series[0].data = value[1] ? value[1].slice(1).map((value, index) => {
//     return {value: value, name: option.legend.data[index]}
//   }) : []
//   myChart.setOption(option);
// })

onMounted(() => {
  initStation().then(() => {
    initEcharts()
    connectStomp()
  })
})

onUnmounted(() => {
  window.removeEventListener("resize", myChart?.resize)
  stomp.unsubscribe('/topic/wc')
})
// onActivated(() => {
//   initEcharts()
// })

const timeRanges = [
  {
    value: 1,
    label: '1秒'
  },
  {
    value: 2,
    label: '2秒'
  },
  {
    value: 5,
    label: '5秒'
  },
  {
    value: 10,
    label: '10秒'
  },
  {
    value: 20,
    label: '20秒'
  },
  {
    value: 30,
    label: '30秒'
  },
]
const samples = [
  {
    value: 1,
    label: '--全部采样点--'
  },
  {
    value: 5,
    label: '--1/5--'
  },
  {
    value: 10,
    label: '--1/10--'
  },
  {
    value: 25,
    label: '--1/25--'
  }
]
const accesses = [
  {
    value: 1,
    label: '--1.2.3--'
  },
  {
    value: 2,
    label: '--4.5.6--'
  }
]
const conditionForm = reactive(({
  station: '',
  timeRange: 5,
  sample: 5,
  access: 1
}))
const stations = ref([])
const initStation = () => {
  return new Promise((resolve) => {
    regionTree().then(res => {
      stations.value = res.data.map((region: {
        code: any; name: any; stationInfoList: any[];regions: any[];
      }) => {
        let regions = region.regions;
        let regionItem = {
          value: region.code,
          label: region.name,
          children: []
        }
        if (!regions){
          return regionItem;
        }
        for (let region1 of regions) {
          regionItem.children.push({
          value: region1.code,
          label: region1.name,
          children: region1.stationInfoList.map(station => {
            if (!props.id && station.online) {
              conditionForm.station = station.id
            }
            const sta = {
              value: station.id,
              label: station.id,
              children: [],
              disabled: station.online != 1
            }
            return sta
          })
        })
        }
        return regionItem
      })
      resolve(stations.value)
    })
  })
}

watch(
    () => props.id,
    (newVal) => {
      conditionForm.station = newVal
      data = []
    },
    {
      immediate: true
    }
)
</script>
<template>
  <div class="panel-wrap">
    <div class="condition">
      <el-form :inline="true" :model="conditionForm" class="con-form" size="default">
        <el-form-item label="站点">
          <el-tree-select v-model="conditionForm.station" :data="stations" placeholder="请选择站点" style="width:180px;"/>
        </el-form-item>
        <el-form-item label="时长">
          <el-select v-model="conditionForm.timeRange" placeholder="请选择时长" style="width:70px;">
            <el-option
                v-for="item in timeRanges"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="采样">-->
<!--          <el-select v-model="conditionForm.sample" placeholder="请选择采样点数" style="width:80px;">-->
<!--            <el-option-->
<!--                v-for="item in samples"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="通道">-->
<!--          <el-select v-model="conditionForm.access" placeholder="请选择通道" style="width:100px;">-->
<!--            <el-option-->
<!--                v-for="item in accesses"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="传感器">
          <el-switch
            v-model="conditionForm.access"
            size="default"
            :active-value="1"
            inline-prompt
            active-text="主传感器"
            inactive-text="备传感器"
          />
        </el-form-item>
      </el-form>
    </div>
    <div :id="chartId" class="real-time-panel"></div>
  </div>
</template>

<style scoped lang="scss">
@import "@/assets/styles/theme";
.panel-wrap {
  padding: 20px 5px;
  height: 100%;
  width: 100%;
  box-sizing: border-box;

  .condition {
    width: 100%;
    .con-form {
      width: 100%;
    }
  }

  .real-time-panel {
    width: 100%;
    height: calc(100% - 40px);
  }
  :deep(.el-form-item__label) {
      color: $table-color;
    }
}

.el-switch {
  --el-switch-on-color: #16c8db;
  --el-switch-off-color: #7da6aa;
}


</style>
